//
//  XSQOAuthViewController.swift
//  WeiBo
//
//  Created by 许世强 on 2017/3/29.
//  Copyright © 2017年 许世强. All rights reserved.
//

import UIKit
import SVProgressHUD

// AppKey
let AppKey = "2934576200"

//App secret
let AppSecret = "bf69eea31bf8776f3ce27e23c0f2d24d"

// 授权回调地址
let Redirect_Uri = "http://www.itcast.cn"

class XSQOAuthViewController: UIViewController {
    
    //懒加载webView控件
    private lazy var webView:UIWebView = UIWebView()
    
    //自定义视图控制器的视图 (这里使用webView控件,而这里webView是懒加载)
    override func loadView(){
        
        //设置代理
        webView.delegate = self
        
        view = webView
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        setupUI()
        
        //调用加载微博登录界面的方法
        requestOAuth()
        
    }

    //加载微博的登录界面
    private func requestOAuth(){
    
        //微博登录界面地址
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_Uri)"
        
        //请求,  这里的地址是存在的,可以强制解包
        let request = URLRequest(url: URL(string: urlStr)!)
        
        //加载web页面
        webView.loadRequest(request)
    }
    
    //设置导航栏按钮和标题  (使用之前抽取的UIBarButton)
    private func setupUI(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        
         navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        
        //标题
        navigationItem.title = "微博登录"
    }
    
    //点击取消按钮事件
    @objc private func cancelAction(){
        
        //disMis
        dismiss(animated: true, completion: nil)
    }

    //点击"自动填充"按钮事件
    @objc private func autoFillAction(){
        
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'hao123guohaibin@163.com';document.getElementById('passwd').value = 'guohaibin123';")
        
    }
    
}

//遵守webView的代理协议
extension XSQOAuthViewController:UIWebViewDelegate{
    
    //将要加载网络请求的代理方法
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //判断是否有请求地址
        guard let urlStr = request.url?.absoluteString else{
            
            //若无
            return false
        }
        
        if !urlStr.hasPrefix(Redirect_Uri){
            
            //表示不是我们想要的请求地址, 但是别的地址还是要正常加载的
            return true
        }
        
        //到这一步,表示是我们想要的请求地址
        //先拿到网页请求的参数, 且判断是否以"code="开头, 再进行截取
        if let query = request.url?.query, query.hasPrefix("code="){
        
            //截取授权码
            let code = query.substring(from: "code=".endIndex)
            
            //将code传入方法,获取令牌
//            requestAccessToken(code: code)
            
            //通过ViewModel单例获取令牌  传入code
            XSQUserAccountViewModel.shareViewModel.requestAccessToken(code: code, callBack: { (isSuccess) in
                
                //如果登录成功
                if isSuccess{
                    
                    //登录成功,先disMis掉以后,当前OAuth控制器才能切换根视图控制器
                    //因为当前控制器是modal出来的
                    self.dismiss(animated: false, completion: { 
                        
                        //发送通知,切换根视图控制器  (进入欢迎页面)
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                    })
                }
                
            })
            
        } else {
            //请求的地址不是以"code="开头的,就是点击了取消授权,直接dismis
            dismiss(animated: true, completion: nil)
        }
        
        //准备加载内容时调用的方法，通过返回值来进行是否加载的设置
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        //展示风火轮
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
    }
    
}
